package com.juyu.miliao.api.service;


import com.juyu.miliao.api.constant.EnergyLevelType;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.mysql.UserVipDao;
import com.juyu.miliao.api.dao.mysql.UserWalletDao;
import com.juyu.miliao.api.dao.redis.VipRedisDao;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.*;
import com.juyu.miliao.api.rabbitMQ.BillDetailBeansMq;
import com.juyu.miliao.api.rabbitMQ.MakeFriendsMq;
import com.juyu.miliao.api.rabbitMQ.UserVipMq;
import com.juyu.miliao.api.util.SystemMessageUtil;
import com.juyu.miliao.common.builder.BillDetailBeansMqMessageBuilder;
import com.juyu.miliao.common.builder.UserVipMqMessageBuilder;
import com.juyu.miliao.common.constant.BeansType;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.constant.VipType;
import com.juyu.miliao.common.domain.dto.BillDetailBeansDTO;
import com.juyu.miliao.common.domain.dto.MakeFriendsMqUserVipTypeDTO;
import com.juyu.miliao.common.domain.dto.UserVipMqMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;

@Service
public class UserVipService {

    private final Logger logger = LoggerFactory.getLogger(UserVipService.class);

    private static final String CTT = ZoneId.SHORT_IDS.get("CTT");

    @Resource
    private UserVipDao userVipDao;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private UserWalletDao userWalletDao;
    @Resource
    private SystemMessageUtil systemMessageUtil;
    @Resource
    private VestRobotMessageService vestRobotMessageService;
    @Resource
    private VipService vipService;

    @Resource
    private UserInfoCache userInfoCache;
    @Resource
    private MakeFriendsMq makeFriendsMq;


    @Autowired
    private EnergyLevelService energyLevelService;

    @Autowired
    private UserVipMq userVipMq;

    @Autowired
    private VipRedisDao vipRedisDao;

    @Autowired
    private BillDetailBeansMq billDetailBeansMq;


    public UserVip getUserVipById(long userId) {
        return userVipDao.getUserVipById(userId);
    }

    /**
     * 购买vip，预写好，应该在支付异步通知接口时调用方法
     *
     * @param userId
     * @param vipId
     * @param contentType 2:普通vip,3:SVIP,4:铂金VIP
     * @param payNum      购买次数
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeUserVip(long userId, int vipId, int contentType, int payNum) throws IOException {
        logger.info("保存VIP充值记录：userId={},vipId={}", userId, vipId);
        UserVip entity = new UserVip();
        entity.setUserId(userId);
        entity.setVipId(vipId);
        //获取充值的vip信息
        Vip vip = vipService.getVipById(vipId);
        //vip类型 1：普通vip,2:svip,3:铂金VIP
//        int vipType = 1;
//        if (vip.getVipClassification() == 1) {
//            vipType = VipType.COMMON_VIP_TYPE.getCode();
//        } else if (vip.getVipClassification() == 2) {
//            vipType = VipType.SUPER_VIP_TYPE.getCode();
//        }else if(vip.getVipClassification() == 3){
//            vipType = VipType.PLATINUM_VIP_TYPE.getCode();
//        }
        //判断用户之前是否有剩余vip时间
        UserVip userVip = userVipDao.getUserVipByUserIdAndVipType(userId, vip.getVipClassification());

        //马甲包需求  存在终身
        int validTime = vip.getValidTime();
        if (validTime == -1) {
            //终身vip改为年VIP
//            userInfoDao.updateUserIsVip(1, vip.getVipPayType(), vip.getVipLevel(), userId);
            validTime = 365;
        }
        if (userVip == null) {
            //无vip 或vip已到期
            entity.setVipDate(validTime*payNum);
            entity.setStatus(1);
            entity.setExpireTime(LocalDateTime.now(ZoneId.of(CTT)).plusDays(validTime * payNum));
            entity.setVipPayType(vip.getVipPayType());
            entity.setVipType(vip.getVipClassification());
            int i = userVipDao.insertUserVip(entity);
            logger.info("保存用户vip信息：i={},entity={}", i, entity);
            if (vip.getVipClassification() == VipType.COMMON_VIP_TYPE.getCode()) {
                userInfoDao.updateUserIsVip(1, vip.getVipPayType(), vip.getVipLevel(), userId);
            } else if(vip.getVipClassification() == VipType.SUPER_VIP_TYPE.getCode()) {
                userInfoDao.updateUserIsSVip(1, userId);
            }else if(vip.getVipClassification() == VipType.PLATINUM_VIP_TYPE.getCode()) {
                userInfoDao.updateUserIsPlatinumVip(1,userId);
            }
            //将vip信息添加到延迟队列中
            addDelay(entity);
        } else {//vip未到期
            int vipPayType = userVip.getVipPayType();
            if (vip.getVipPayType() > vipPayType) {
                vipPayType = vip.getVipPayType();
            }
            userVipDao.updateUserVipStatusByUserVipId(userVip.getUserVipId());
            entity.setVipDate(userVip.getVipDate() + vip.getValidTime()*payNum);
            entity.setStatus(1);
            entity.setVipPayType(vipPayType);
            entity.setVipType(vip.getVipClassification());
            entity.setExpireTime(userVip.getExpireTime().plusDays(vip.getValidTime() * payNum));
            userVipDao.insertUserVip(entity);
            if (vip.getVipClassification() == VipType.COMMON_VIP_TYPE.getCode()) {
                userInfoDao.updateUserIsVip(1, vip.getVipPayType(), vip.getVipLevel(), userId);
            } else if(vip.getVipClassification() == VipType.SUPER_VIP_TYPE.getCode()) {
                userInfoDao.updateUserIsSVip(1, userId);
            }else if(vip.getVipClassification() == VipType.PLATINUM_VIP_TYPE.getCode()) {
                userInfoDao.updateUserIsPlatinumVip(1,userId);
            }
            //将vip信息添加到延迟队列中
            addDelay(entity);
        }
        //充值vip添加用户能量
        addUserCountEnergy(vipId,userId, payNum);
        //充值vip添加用户寻豆
        addUserWalletBeans(vipId,userId);

        //User表:have_been_vip   tinyint(1)   是否为vip,历史冲过vip的就算vip,(0-false 1-true)
//        userInfoDao.updateUserInfoHaveBeenVip(userId);

        //2018-11-02马甲包需求 冲vip送金币
        Integer giveCorn = vip.getGiveCorn();
        if (giveCorn != null && giveCorn != 0) {
            addUserWallet(userId, giveCorn);
        }

        if(entity.getVipType() == VipType.COMMON_VIP_TYPE.getCode()){
            systemMessageUtil.userVip(userId);

        }else if(entity.getVipType() == VipType.SUPER_VIP_TYPE.getCode()){
            systemMessageUtil.userSVip(userId);
        }else if(entity.getVipType() == VipType.PLATINUM_VIP_TYPE.getCode()){
            systemMessageUtil.userPlatinumVip(userId);

        }

        User user = userInfoDao.getUserInfoById(userId);
        if(user.getIsVideo() == 1) {
            //充值用户使用系统账号发送给在线女主播
            vestRobotMessageService.getSendMsgByHost(userId, vip.getPrice() + "", EnumType.VIP);
        }
        //更新userinfo
        userInfoCache.deleteUserCacheInfo(userId);
        MakeFriendsMqUserVipTypeDTO makeFriendsMqUserVipTypeDTO = new MakeFriendsMqUserVipTypeDTO();
        makeFriendsMqUserVipTypeDTO.setIsVip(1);
        makeFriendsMqUserVipTypeDTO.setUserId(user.getUserId());
        makeFriendsMq.sendUserVipType(makeFriendsMqUserVipTypeDTO);
    }

    private void addDelay(UserVip entity) {

        UserVipMqMessageBuilder userVipMqMessageBuilder = new UserVipMqMessageBuilder();

        UserVipMqMessage userVipMqMessage = userVipMqMessageBuilder.expireTime(entity.getExpireTime())
                .userId(entity.getUserId()).userVipId(entity.getVipId())
                .userVipId(entity.getUserVipId()).build();

        userVipMq.sendUserVipMqMessage(userVipMqMessage);
    }


    private void addUserWallet(long userId, int deposit) {
        UserWallet userWallet = new UserWallet();
        userWallet.setUserId(userId);
        userWallet.setDeposit(deposit);
        userWalletDao.reviseDeposit(userWallet);
    }

    /**
     * 充值vip 添加能量
     *
     * @param vipId
     * @param userId
     * @param payNum
     */
    private void addUserCountEnergy(int vipId, long userId, int payNum) throws IOException {

        Vip vip = vipRedisDao.getVipInfoById(vipId);
        int energy = vip.getPayGiveEnergy() * payNum;
        logger.info("用户=" + userId + "|充值vip将要添加能量：" + energy);
        energyLevelService.addUserEnergyLevel(userId, EnergyLevelType.ENERGY_TYPE_VIP, energy);

    }

    /**
     * 充值vip 添加寻豆
     *
     * @param vipId
     * @param userId
     */
    private void addUserWalletBeans(int vipId, long userId) throws IOException {

        BillDetailBeansMqMessageBuilder builder = new BillDetailBeansMqMessageBuilder();

        Vip vip = vipRedisDao.getVipInfoById(vipId);
        long beans = vip.getPayGiveBeans();
        if(vip.getVipClassification()==VipType.COMMON_VIP_TYPE.getCode()){
            builder.beansType(BeansType.PAY_VIP_ADD_BEANS);
        }else if(vip.getVipClassification()==VipType.SUPER_VIP_TYPE.getCode()){
            builder.beansType(BeansType.PAY_SUPER_VIP_ADD_BEANS);
        }else if(vip.getVipClassification() == VipType.PLATINUM_VIP_TYPE.getCode()){
            builder.beansType(BeansType.PAY_PLATINUM_VIP_ADD_BEANS);
        }
        BillDetailBeansDTO billDetailBeansDTO = builder.userId(userId).beans(beans)
                .createDate(LocalDate.now(ZoneOffset.of("+8")))
                .createTime(LocalDateTime.now(ZoneOffset.of("+8"))).build();

        UserWallet userWallet = new UserWallet();
        userWallet.setBeans(billDetailBeansDTO.getBeans());
        userWallet.setUserId(billDetailBeansDTO.getUserId());
        int flag = userWalletDao.plusUserWalletBeans(userWallet);
        if(flag>0){
            billDetailBeansMq.getBillDetailBeansMq(billDetailBeansDTO);
        }

    }
    /**
     * 马甲包需求：vip充值
     * @param userId
     * @param hostUserId
     * @param vipId
     * @param orderId
     */
//	public void vestUserVip(String userId,String hostUserId ,String vipId,String orderId){
//		//获取充值的vip信息
//		Vip vip = VipCache.INSTANCE.getVipById(Integer.parseInt(vipId));
//		VipPay vipPay = new VipPay();
//		vipPay.setHostUserId(Integer.parseInt(hostUserId));
//		vipPay.setBuyUserId(Integer.parseInt(userId));
//		vipPay.setVipId(Integer.parseInt(vipId));
//		vipPay.setValidTime(vip.getValidTime());
//		vipPay.setVipStatus(1);
//		vipPay.setVipPayType(vip.getVipPayType());
//		vipPay.setOrderId(orderId);
//
//		/** 同城夜聊支付类型 1畅聊 2qq 3微信 4全部*/
//		if(vipPay.getVipPayType()==2 || vipPay.getVipPayType()==4)
//			vipPay.setQq(AppkeyCache.INSTANCE.getAppkey("vest_tcyl_qq").getValue());
//		if(vipPay.getVipPayType()==3 || vipPay.getVipPayType()==4)
//			vipPay.setWx(AppkeyCache.INSTANCE.getAppkey("vest_tcyl_wx").getValue());
//		vipPayDao.insertVipPay(vipPay);
//		userInfoDao.updateUserIsVip(1,Long.parseLong(userId));
//	}


}
